# -*- coding: utf-8 -*-
# filename: handle.py

import web

HTML_PAGE = '''
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        //  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        // IE6, IE5 浏览器执行代码
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            //document.getElementById("myBtn").setAttribute("disabled", "disabled");
            document.getElementById("myBtn").style.visibility="hidden";
            document.getElementById("smBtn").style.visibility="hidden";
        }
    }
    xmlhttp.open("GET","./ajax_info.txt",true); // 在此处修改文件路径
    xmlhttp.send();

    window.scrollTo(0,document.body.scrollHeight); // 自动滚动到浏览器底部
    setTimeout("loadXMLDoc()",1000); // 递归调用
    //loadXMLDoc(); // 先执行一次 
}
</script>
</head>
<body>

<div id="myDiv">HaydnLiao</div>
<form action="/" method="post">
<input type="hidden" name="cmd" value="r"/>
<button id="smBtn" type="submit">New</button>
<button id="myBtn" type="button" onclick="loadXMLDoc()">Continue</button>
</form>

</body>
</html>
'''
AJAX_FILE_NAME = './ajax_info.txt'
MAX_LOG_NUM = 1000
RESET_FLAG = False

def getHtmlPage():
    global HTML_PAGE
    return HTML_PAGE

def setResetFlag(value):
    global RESET_FLAG
    RESET_FLAG = value

def getResetFlag():
    global RESET_FLAG
    return RESET_FLAG

def getMaxLogNum():
    global MAX_LOG_NUM
    return MAX_LOG_NUM

def getAjaxFileName():
    global AJAX_FILE_NAME
    return AJAX_FILE_NAME

class Handle(object):
    def GET(self, fn):
        # print '<Handle>get'
        if fn != '':
            try:
                with open(fn, "rb") as fs:
                    return fs.read()
            except Exception, err:
                print '>>>GET>>>', err
        return getHtmlPage()

    def POST(self, fn):
        # print '<Handle>post'
        postData = web.input()
        cmd = postData['cmd']
        # print cmd
        if cmd == 'r':
            setResetFlag(True)
            return getHtmlPage() + "<script>loadXMLDoc();</script>"
        return getHtmlPage()



